<template>
  <div class="login-form-wrapper">
    <div class="login-form-title">病人术后随访系统后台</div>
    <div class="login-form-sub-title">欢迎使用随访系统～</div>
    <div class="login-form-error-msg">{{ errorMessage }}</div>
    <a-form
      ref="loginForm"
      :model="userInfo"
      class="login-form"
      layout="vertical"
      @submit="handleSubmit"
    >
      <a-form-item
        field="username"
        :rules="[{ required: true, message: '请输入用户名' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input v-model="userInfo.username" placeholder="请输入用户名">
        </a-input>
      </a-form-item>
      <a-form-item
        field="password"
        :rules="[{ required: true, message: '请输入密码' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input-password
          v-model="userInfo.password"
          placeholder="请输入密码"
          allow-clear
        >
        </a-input-password>
      </a-form-item>
      <a-form-item
        field="code"
        :rules="[{ required: true, message: '请输入验证码' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <div class="code">
          <div class="input">
            <a-input
              v-model="userInfo.code"
              placeholder="请输入验证码"
              allow-clear
            >
            </a-input>
          </div>
          <div class="img" @click="getCaptcha">
            <a-image :preview="false" width="100" height="38" :src="codeSrc" />
          </div>
        </div>
      </a-form-item>
      <a-space :size="16" direction="vertical">
        <div class="login-form-password-actions">
          <a-checkbox
            checked="rememberPassword"
            :model-value="loginConfig.rememberPassword"
            @change="setRememberPassword"
          >
            记住密码
          </a-checkbox>
          <a-link>忘记密码</a-link>
        </div>
        <a-button
          class="submit-btn"
          type="primary"
          html-type="submit"
          long
          :loading="loading"
        >
          登录
        </a-button>
        <!-- <a-button type="text" long class="login-form-register-btn">
          {{ $t('login.form.register') }}
        </a-button> -->
      </a-space>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { useUserStore } from '@/store';
  import { useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import useLoading from '@/hooks/loading';
  import { useStorage } from '@vueuse/core';
  import { getCaptchaImage } from '@/api/user';
  import type { LoginData } from '@/api/user';

  // eslint-disable-next-line no-underscore-dangle
  const router = useRouter();
  const { loading, setLoading } = useLoading();
  const errorMessage = ref('');
  const codeSrc = ref('');

  const loginConfig = useStorage(
    `${import.meta.env.VITE_PROJECT_KEY}-login-config`,
    {
      rememberPassword: true,
      username: 'admin', // 演示默认值
      password: '123456', // demo default value
    }
  );
  const userInfo = reactive({
    username: loginConfig.value.username,
    password: loginConfig.value.password,
    code: '',
  });
  const userStore = useUserStore();
  // 登录
  const handleSubmit = async ({
    errors,
    values,
  }: {
    errors: Record<string, ValidatedError> | undefined;
    values: Record<string, any>;
  }) => {
    if (!errors) {
      setLoading(true);
      try {
        const { code, msg } = await userStore.login(values as LoginData);
        if (code !== 200) {
          Message.error(msg);
          return;
        }
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const { redirect, ...othersQuery } = router.currentRoute.value.query;
        router.push({
          // name: (redirect as string) || 'Dashboard',
          name: 'Dashboard',
          query: {
            ...othersQuery,
          },
        });
        Message.success('登录成功');
        const { rememberPassword } = loginConfig.value;
        const { username, password } = values;
        // 实际生产环境需要进行加密存储。
        // The actual production environment requires encrypted storage.
        loginConfig.value.username = rememberPassword ? username : '';
        loginConfig.value.password = rememberPassword ? password : '';
      } catch (err) {
        errorMessage.value = (err as Error).message;
      } finally {
        setLoading(false);
      }
    }
  };
  // 获取验证码
  const getCaptcha = async () => {
    getCaptchaImage().then(({ code, img, msg }) => {
      if (code !== 200) {
        Message.error(msg);
        return;
      }
      codeSrc.value = `data:image/gif;base64,${img}`;
    });
  };
  getCaptcha();
  const setRememberPassword = (value: any) => {
    loginConfig.value.rememberPassword = value;
  };
</script>

<style lang="less" scoped>
  :deep(.arco-input-wrapper) {
    background-color: transparent !important;
    border-color: transparent;
    border-bottom: 1px solid rgb(var(--primary-6));
    padding-right: 0;
    padding-left: 0;
  }
  :deep(.arco-input-wrapper.arco-input-error) {
    border-bottom: 1px solid rgb(var(--danger-6));
  }
  :deep(.arco-input-wrapper.arco-input-error:focus-within) {
    border-color: transparent;
    border-bottom: 1px solid rgb(var(--danger-6));
  }
  :deep(.arco-input-wrapper .arco-input.arco-input-size-medium) {
    line-height: 1.8;
  }

  .login-form {
    &-wrapper {
      width: 575px;
    }

    &-title {
      font-weight: 500;
      margin-bottom: 16px;
      font-size: 32px;
      color: #4370f8;
      line-height: 48px;
      letter-spacing: 2px;
    }

    &-sub-title {
      font-size: 14px;
      font-weight: 400;
      color: #333333;
      line-height: 20px;
      letter-spacing: 1px;
      margin-bottom: 100px;
    }

    &-error-msg {
      height: 32px;
      color: rgb(var(--red-6));
      line-height: 32px;
    }

    &-password-actions {
      display: flex;
      justify-content: space-between;
    }

    &-register-btn {
      color: var(--color-text-3) !important;
    }
    .submit-btn {
      width: 100%;
      height: 40px;
      border-radius: 8px 8px 8px 8px;
      opacity: 1;
    }
    .code {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      .input {
        width: calc(100% - 120px);
      }
      .img {
        width: 100px;
      }
    }
  }
</style>
